import { createRouter, createWebHashHistory, createWebHistory, type RouteLocationNormalized } from "vue-router";
import routes from "./routes";
import { useCachedViewStoreHook } from "@/store/modules/cached-view";
import NProgress from "@/utils/progress";
import setPageTitle from "@/utils/set-page-title";
import { getAuth } from "@/api";

const router = createRouter({
    history: createWebHistory(),
    routes
});

export interface toRouteType extends RouteLocationNormalized {
    meta: {
        title?: string;
        noCache?: boolean;
    };
}
console.log("router-index.ts");
let token = ""; // 标志变量，记录是否已经调用过
router.beforeEach(async (to: toRouteType, from, next) => {
    // NProgress.start();
    try {
        if (to.name === "Index") {
            useCachedViewStoreHook().delAllCachedViews(); // 从二级页面返回首页时清除缓存
        }
        useCachedViewStoreHook().addCachedView(to);
        if (token) {
            // 路由缓存

            next();
            return;
        }
        const res = await getAuth({
            authorization: window.TongBridge.clientInfo.user.token,
            userId: window.TongBridge.clientInfo.user.userId,
            avatar: window.TongBridge.clientInfo.user.avatar
        });
        const newToken = res.data.accessToken;
        localStorage.setItem("token", newToken);
        token = newToken;
        // 路由缓存
        useCachedViewStoreHook().addCachedView(to);
        // 页面 title
        setPageTitle(to.meta.title);
        next();
    } catch (error) {
        console.error("Token 请求失败:", error);
    }
});

router.afterEach(() => {
    console.log("afterEach111");

    NProgress.done();
});

export default router;
